<?php

namespace Wintel\RestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class WebcallController
 *
 * @package Wintel\RestBundle\Controller
 */
class WebcallController extends Controller
{
    /**
     * webcall呼入通话记录
     *
     * @param Request $request The Request Object
     *
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function webcall400Action(Request $request)
    {
        $vcc_id = $request->get("vcc_id", 0);
        $start_time = $request->get("start_time", 0);
        $end_time = $request->get("end_time", 0);

        if (empty($vcc_id)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空',
            );
            return new JsonResponse($ret);
        }
        if (!is_numeric($vcc_id)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符',
            );
            return new JsonResponse($ret);
        }
        if (empty($start_time)) {
            $ret = array(
                'code' => 403,
                'message' => '开始时间为空',
            );
            return new JsonResponse($ret);
        }

//        if (empty($end_time)) {
//            $ret = array(
//                'code' => 404,
//                'message' => '结束时间为空',
//            );
//            return new JsonResponse($ret);
//        }
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get('doctrine.dbal.default_connection');
        if (!empty($end_time)) {
            $where = ' AND  w.start_time <= :end_time ';
            $par_arr = array(
                'vcc_id' => $vcc_id,
                'start_time' => $start_time,
                'end_time' => $end_time,
            );
        } else {
            $where = '';
            $par_arr = array(
                'vcc_id' => $vcc_id,
                'start_time' => $start_time,
            );
        }
        $result = $conn->fetchAll(
            'SELECT w.call_id,w.caller,w.called,w.ivr_digits,w.result,w.start_time,w.conn_time,
             w.end_time,w.all_secs,r.record_file '.
            ' FROM win_incdr as w LEFT JOIN win_agcdr as r ON w.call_id = r.call_id﻿ and w.vcc_id=r.vcc_id '.
            'WHERE w.vcc_id=:vcc_id AND w.start_time>=:start_time '.$where.' LIMIT 3000',
            $par_arr
        );
        $data = $temp = array();
        if (!empty($result)) {
            foreach ($result as $v) {
                $temp['caller'] = $v['caller'];
                $temp['called'] = $v['called'];
                $temp['call_id'] = $v['call_id'];
                $temp['ivr_digits'] = $v['ivr_digits'];
                $temp['in'] = 'in';
                $temp['start_time'] = empty($v['start_time']) ? '' : date('Y-m-d H:i:s', $v['start_time']);
                $temp['conn_time'] =  empty($v['conn_time']) ? '' : date('Y-m-d H:i:s', $v['conn_time']);
                $temp['end_time'] = empty($v['end_time']) ? '' : date('Y-m-d H:i:s', $v['end_time']);
                $temp['all_secs'] = $v['all_secs'];
                $temp['record_file'] = $v['record_file'];
                $temp['result'] = $v['result']==0 ? '接通' : '未接通';
                $data[] = $temp;
            }
        }
        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'data' => $data,
        );
        return new JsonResponse($ret);
    }

    /**
     * webcall回呼通话记录
     *
     * @param Request $request The Request Object
     *
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function webcall800Action(Request $request)
    {
        $vcc_id = $request->get("vcc_id", 0);
        $vcc_code = $request->get("vcc_code", 0);
        $start_time = $request->get("start_time", 0);
        $end_time = $request->get("end_time", 0);
        $recordApiUrl = $this->container->getParameter('record_api_url');
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get('doctrine.dbal.default_connection');
        if (empty($vcc_id)) {
            $msg = $vcc_id = $this->container->get('validator.custom')->checkVccCode($vcc_code);
            if (!empty($msg) && is_array($msg)) {
                return new JsonResponse($msg);
            }
        } else {
            if (!is_numeric($vcc_id)) {
                $ret = array(
                    'code' => 404,
                    'message' => '企业ID包含非数字字符',
                );
                return new JsonResponse($ret);
            }
            //判断企业ID 是否存在；
            $vcc_code = $conn->fetchColumn(
                "SELECT vcc_code FROM cc_ccods WHERE status=1 AND vcc_id = :vcc_id",
                array('vcc_id' => $vcc_id)
            );
            if (empty($vcc_code)) {
                $ret = array(
                    'code' => 405,
                    'message' => '企业ID不存在',
                );
                return new JsonResponse($ret);
            }
        }
        $user = $this->getUser();
        if (empty($user) || $user->getVccId() != $vcc_id) {
            return new JsonResponse(array('code'=>406, 'message'=>'未验证通过或企业信息填写错误'));
        }
        if (empty($start_time)) {
            $ret = array(
                'code' => 403,
                'message' => '开始时间为空',
            );
            return new JsonResponse($ret);
        }

        if (!empty($end_time)) {
            $where = ' AND  w.start_time <= :end_time ';
            $par_arr = array(
                'vcc_id' => $vcc_id,
                'start_time' => $start_time,
                'end_time' => $end_time,
            );
        } else {
            $where = '';
            $par_arr = array(
                'vcc_id' => $vcc_id,
                'start_time' => $start_time,
            );
        }

        $result = $conn->fetchAll(
            'SELECT w.caller,w.called,w.result,w.start_time,w.conn_time,w.call_id,
             w.end_time,w.all_sec '.
            ' FROM ac_cdr as w LEFT JOIN win_agcdr as r ON w.call_id = r.call_id and w.vcc_id=r.vcc_id '.
            'WHERE w.vcc_id=:vcc_id AND w.start_time >= :start_time '.$where.' lIMIT 3000',
            $par_arr
        );
        $data = $temp = array();
        if (!empty($result)) {
            foreach ($result as $v) {
                $temp['caller'] = $v['caller'];
                $temp['called'] = $v['called'];
                $temp['out'] = 'out';
                $temp['start_time'] = empty($v['start_time']) ? '' : date('Y-m-d H:i:s', $v['start_time']);
                $temp['conn_time'] =  empty($v['conn_time']) ? '' : date('Y-m-d H:i:s', $v['conn_time']);
                $temp['end_time'] = empty($v['end_time']) ? '' : date('Y-m-d H:i:s', $v['end_time']);
                $temp['all_secs'] = $v['all_sec'];
                //$temp['record_file'] = $v['record_file'];
                //接通才有录音；
                $temp['record_file'] = $v['result'] == 0 ? $recordApiUrl.'/out/'.$vcc_id.'/'.$v['call_id'] : '';
                $temp['call_id'] = $v['call_id'];
                $temp['result'] = $v['result']==0 ? '接通' : '未接通';
                $data[] = $temp;
            }
        }
        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'data' => $data,
        );
        return new JsonResponse($ret);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * 华硕800cdr;
     */
    public function cdr800Action(Request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");
        $info = $request->get("info", '');
        //分页搜索相关信息；
        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return new JsonResponse(array('code' => 401, 'message'=>'info格式非json'));
            }
        }
        $where = '';
        if (isset($addInfo['filter'])) {
            //开始时间
            if (isset($addInfo['filter']['ivr_time']) && !empty($addInfo['filter']['ivr_time'])) {
                $start_time = $addInfo['filter']['ivr_time'];
                $msg = $this->get('validator.extend.custom')->isDateTime('开始时间格式不正确', $start_time, 404);
                if (!empty($msg) && is_array($msg)) {
                    return new JsonResponse($msg);
                }
                $where.="AND ivr_time >= UNIX_TIMESTAMP('$start_time')";
            }

            //结束时间
            if (isset($addInfo['filter']['end_time']) && !empty($addInfo['filter']['end_time'])) {
                $end_time = $addInfo['filter']['end_time'];
                $msg = $this->get('validator.extend.custom')->isDateTime('结束时间格式不正确', $end_time, 405);
                if (!empty($msg) && is_array($msg)) {
                    return new JsonResponse($msg);
                }
                $where.="AND ivr_time <= UNIX_TIMESTAMP('$end_time')";
            }
            //主叫号码
            $where.= isset($addInfo['filter']['real_caller']) && !empty($addInfo['filter']['real_caller']) ?
                " AND real_caller IN (".$addInfo['filter']['real_caller'].") " : '';

            //呼叫状态， (0 未呼通,1 呼通)
            $where.= isset($addInfo['filter']['call_result']) && $addInfo['filter']['call_result'] !== false ?
                " AND call_result = '".$addInfo['filter']['call_result']."' " : '';

            //被叫号码
            $where.= isset($addInfo['filter']['called']) && !empty($addInfo['filter']['called']) ?
                " AND called LIKE '%".$addInfo['filter']['called']."%' " : '';

            //传过来条件
            $where.= isset($addInfo['filter']['condition']) && !empty($addInfo['filter']['condition']) ?
                $addInfo['filter']['condition'] : '' ;
        }
        $count = $conn->fetchColumn(
            'SELECT count(*) '.
            'FROM win_800cdr '.
            'WHERE vcc_id = 0 '.$where
        );
        $page = $this->get("validator.extend.custom")->getPageInfo($count, 'win_800cdr', $addInfo);
        //默认给all_sec 排序
        $page['sort'] = $page['sort'] == 1 ? 'all_sec' : $page['sort'];
        $list = $conn->fetchAll(
            'SELECT real_caller,called,ivr_time,end_time,end_time-ivr_time AS all_sec,call_result '.
            'FROM win_800cdr '.
            "WHERE vcc_id = 0 ".$where.
            'ORDER BY '.$page['sort'].' '.$page['order'].' LIMIT '.$page['start'].','.$page['limit']
        );
        $res = array();
        if (!empty($list)) {
            foreach ($list as $row) {
                switch ($row["call_result"]) {
                    case 0: $row["call_result"] = "未呼通";
                        break;
                    case 1: $row["call_result"] = "呼通";
                        break;
                    default:$row["call_result"] = "未呼通";
                        break;
                }
                $row["ivr_time"] = $row["ivr_time"] ? date("Y-m-d H:i:s", $row["ivr_time"]) : "";
                $row["end_time"]   = $row["end_time"]   ? date("Y-m-d H:i:s", $row["end_time"])   : "";
                $res[] = $row;
            }
        }
        return new JsonResponse(array('code'=>'200','message'=>'ok','total'=>$count,'data'=>$res));
    }
}
